from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from django.utils import timezone


class StandardPagination(PageNumberPagination):
    """标准分页器 - 返回统一格式的分页响应"""
    page_size = 20
    page_size_query_param = 'page_size'
    max_page_size = 100

    def get_paginated_response(self, data):
        return Response({
            'code': 200, 'message': '获取成功',
            'data': {
                'items': data, 'total': self.page.paginator.count,
                'page': self.page.number, 'page_size': self.get_page_size(self.request),
                'total_pages': self.page.paginator.num_pages,
                'has_next': self.page.has_next(), 'has_previous': self.page.has_previous(),
            },
            'timestamp': timezone.now().isoformat()
        })

    def get_paginated_response_schema(self, schema):
        return {
            'type': 'object',
            'properties': {
                'code': {'type': 'integer', 'example': 200},
                'message': {'type': 'string', 'example': '获取成功'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'items': schema,  # 🔑 关键：直接使用传入的schema
                        'total': {'type': 'integer'}, 'page': {'type': 'integer'},
                        'page_size': {'type': 'integer'}, 'total_pages': {'type': 'integer'},
                        'has_next': {'type': 'boolean'}, 'has_previous': {'type': 'boolean'}
                    }
                },
                'timestamp': {'type': 'string', 'format': 'date-time'}
            }
        }
